package com.alstudio.utils.distributor.versioncheck;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;

import com.alstudio.R;
import com.alstudio.ui.base.BaseActivity;
import com.alstudio.utils.ALActivityManager;
import com.alstudio.utils.android.net.ALConnectionManager;
import com.alstudio.utils.android.net.ALConnectionManager.ALConnectionType;
import com.alstudio.utils.log.Mylog;
import com.alstudio.view.toast.MyToast;
import com.alstudio.view.toast.MyToastUtil;

public class VersionManager implements NewVersionListener {

	private static VersionManager instance;

	private boolean isVersionChecked = false;

	private boolean isNewVersionArraived = false;

	public VersionManager() {
		VersionCheckUtils.getInstance().setNewVersionAlertListener(this);
	}

	public static VersionManager getInstance() {
		if (instance == null) {
			instance = new VersionManager();
		}
		return instance;
	}

	public boolean isVersionChecked() {
		return isVersionChecked;
	}

	public boolean isNewVersionArraived() {
		return isNewVersionArraived;
	}

	public void checkNewVersion(String currentVersion) {

		if (ALConnectionManager.getConnectionType() == ALConnectionType.TYPE_NONE) {
			return;
		}

		if (TextUtils.isEmpty(currentVersion)) {
			Mylog.e("current version should not null!");
			return;
		}

		final String msg = "<query platform=\"Android\" version=\""
				+ currentVersion + "\"/>";
		Mylog.d("write to server by socket connection: " + msg);

		MyToast toast = new MyToast();
		BaseActivity a = ALActivityManager.getALActivityManager()
				.getCurrentActivity();
		if (a == null) {
			return;
		}
		toast.setContext(a);
		LayoutInflater inflater = a.getLayoutInflater();
		View v = inflater.inflate(R.layout.base_waiting_progress_toast, null);
		toast.setView(v);
		MyToastUtil.showCustomViewToast(toast, Gravity.CENTER);
		VersionCheckUtils.getInstance().checkVersion("116.254.203.70", "9225",
				msg, false, true);
	}

	@Override
	public void onNewVersionArraived(CheckNewVersionResult result) {
		// TODO Auto-generated method stub
		if (result != null) {
			BaseActivity a = ALActivityManager.getALActivityManager()
					.getCurrentActivity();
			if (a == null) {
				return;
			}

			 MyToastUtil.showToastOnTop(a, "有更新 " + result.getWhatsNew(),
			 2000);
		}
	}

	@Override
	public void onConnectSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onConnectFail(String reason) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCheckNewVersionFailed(String reason) {
		// TODO Auto-generated method stub
		BaseActivity a = ALActivityManager.getALActivityManager()
				.getCurrentActivity();
		if (a == null) {
			return;
		}
		MyToastUtil.showToastOnTop(a, "检测更新失败: " + reason, 4000);
	}

}
